package com.vibeplayer.app.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioAttributes;
import android.media.AudioFocusRequest;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Binder;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaDescriptionCompat;
import android.support.v4.media.MediaMetadataCompat;
import android.support.v4.media.session.MediaControllerCompat;
import android.support.v4.media.session.MediaSessionCompat;
import android.support.v4.media.session.PlaybackStateCompat;
import android.view.KeyEvent;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.media.MediaBrowserServiceCompat;

import com.vibeplayer.app.MainActivity;
import com.vibeplayer.app.R;
import com.vibeplayer.app.db.DatabaseHelper;
import com.vibeplayer.app.model.Song;
import com.vibeplayer.app.util.MediaScanner;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import android.annotation.SuppressLint;

/**
 * 音乐播放服务，负责后台播放音乐
 */
public class MusicPlayerService extends MediaBrowserServiceCompat implements
        MediaPlayer.OnPreparedListener,
        MediaPlayer.OnErrorListener,
        MediaPlayer.OnCompletionListener,
        AudioManager.OnAudioFocusChangeListener {

    private static final String CHANNEL_ID = "VibePlayerChannel";
    private static final int NOTIFICATION_ID = 1;
    private static final String MEDIA_ROOT_ID = "media_root_id";
    private static final String EMPTY_MEDIA_ROOT_ID = "empty_root_id";
    
    // 播放模式
    public static final int PLAY_MODE_NORMAL = 0;    // 顺序播放
    public static final int PLAY_MODE_REPEAT_ONE = 1; // 单曲循环
    public static final int PLAY_MODE_REPEAT_ALL = 2; // 列表循环
    public static final int PLAY_MODE_SHUFFLE = 3;    // 随机播放
    
    private MediaPlayer mediaPlayer;
    private MediaSessionCompat mediaSession;
    private PlaybackStateCompat.Builder stateBuilder;
    private AudioManager audioManager;
    private AudioFocusRequest audioFocusRequest;
    
    private final IBinder musicBinder = new MusicBinder();
    private List<Song> songs = new ArrayList<>();
    private int currentSongIndex = -1;
    private int playMode = PLAY_MODE_NORMAL;
    private boolean isPrepared = false;
    private boolean wasPlaying = false; // 用于音频焦点恢复
    private final Random random = new Random();
    private MediaScanner mediaScanner;
    private DatabaseHelper databaseHelper;
    private BroadcastReceiver mediaButtonReceiver;
    
    @Override
    public void onCreate() {
        super.onCreate();
        
        // 1. 初始化基础组件
        mediaScanner = new MediaScanner(this);
        databaseHelper = DatabaseHelper.getInstance(this);
        
        // 2. 初始化MediaSession
        Intent mediaIntent = new Intent(this, MainActivity.class);
        PendingIntent sessionActivity = PendingIntent.getActivity(this, 0, mediaIntent,
                PendingIntent.FLAG_IMMUTABLE);
                
        mediaSession = new MediaSessionCompat(this, "VibePlayerSession");
        mediaSession.setSessionActivity(sessionActivity);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS |
                MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
                
        // 注册媒体按钮广播接收器
        mediaButtonReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction())) {
                    KeyEvent event;
                    if (Build.VERSION.SDK_INT >= 33) { // Android 13 (TIRAMISU)
                        event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT, KeyEvent.class);
                    } else {
                        event = intent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                    }
                    if (event != null) {
                        mediaSession.getController().dispatchMediaButtonEvent(event);
                    }
                }
            }
        };
        
        // 使用SuppressLint注解忽略RECEIVER_NOT_EXPORTED警告
        @SuppressLint("UnspecifiedRegisterReceiverFlag")
        IntentFilter filter = new IntentFilter(Intent.ACTION_MEDIA_BUTTON);
        
        // 使用不同的注册方法，适应不同Android版本
        if (Build.VERSION.SDK_INT >= 33) {
            // Android 13+: 使用RECEIVER_NOT_EXPORTED标志
            registerReceiver(mediaButtonReceiver, filter, Context.RECEIVER_NOT_EXPORTED);
        } else {
            // 低版本Android: 使用标准方法
            registerReceiver(mediaButtonReceiver, filter);
        }
                
        setSessionToken(mediaSession.getSessionToken());
        
        // 3. 初始化播放状态
        stateBuilder = new PlaybackStateCompat.Builder()
                .setActions(PlaybackStateCompat.ACTION_PLAY |
                        PlaybackStateCompat.ACTION_PAUSE |
                        PlaybackStateCompat.ACTION_SKIP_TO_NEXT |
                        PlaybackStateCompat.ACTION_SKIP_TO_PREVIOUS |
                        PlaybackStateCompat.ACTION_STOP |
                        PlaybackStateCompat.ACTION_SEEK_TO);
        mediaSession.setPlaybackState(stateBuilder.build());
        
        // 4. 设置回调
        mediaSession.setCallback(new MediaSessionCallback());
        
        // 5. 初始化MediaPlayer
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .build());
                
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
        
        // 6. 激活MediaSession
        mediaSession.setActive(true);
        
        // 7. 初始化AudioManager
        audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
        
        // 8. 创建通知通道
        createNotificationChannel();
        
        // 9. 启动前台服务
        startForeground(NOTIFICATION_ID, createNotification());
    }
    
    @Override
    public void onDestroy() {
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        
        if (mediaSession != null) {
            mediaSession.setActive(false);
            mediaSession.release();
            mediaSession = null;
        }
        
        if (mediaButtonReceiver != null) {
            unregisterReceiver(mediaButtonReceiver);
            mediaButtonReceiver = null;
        }
        
        abandonAudioFocus();
        
        super.onDestroy();
    }
    
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return musicBinder;
    }
    
    @Override
    public BrowserRoot onGetRoot(@NonNull String clientPackageName, int clientUid, 
            @Nullable Bundle rootHints) {
        // 验证客户端权限
        if (allowBrowsing(clientPackageName)) {
            return new BrowserRoot(MEDIA_ROOT_ID, null);
        } else {
            return new BrowserRoot(EMPTY_MEDIA_ROOT_ID, null);
        }
    }
    
    @Override
    public void onLoadChildren(@NonNull String parentId,
            @NonNull Result<List<MediaBrowserCompat.MediaItem>> result) {
        result.detach();
        
        if (EMPTY_MEDIA_ROOT_ID.equals(parentId)) {
            result.sendResult(Collections.emptyList());
            return;
        }
        
        // 加载媒体项
        List<MediaBrowserCompat.MediaItem> mediaItems = new ArrayList<>();
        for (Song song : songs) {
            MediaDescriptionCompat description = new MediaDescriptionCompat.Builder()
                    .setMediaId(String.valueOf(song.getId()))
                    .setTitle(song.getTitle())
                    .setSubtitle(song.getArtist())
                    .setIconUri(mediaScanner.getAlbumArtUri(song.getAlbumId()))
                    .build();
                    
            mediaItems.add(new MediaBrowserCompat.MediaItem(description,
                    MediaBrowserCompat.MediaItem.FLAG_PLAYABLE));
        }
        
        result.sendResult(mediaItems);
    }
    
    private boolean allowBrowsing(String clientPackageName) {
        return getPackageName().equals(clientPackageName);
    }
    
    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
        mediaPlayer.setAudioAttributes(new AudioAttributes.Builder()
                .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                .setUsage(AudioAttributes.USAGE_MEDIA)
                .build());
        mediaPlayer.setOnPreparedListener(this);
        mediaPlayer.setOnCompletionListener(this);
        mediaPlayer.setOnErrorListener(this);
    }
    
    private class MediaSessionCallback extends MediaSessionCompat.Callback {
        @Override
        public void onPlay() {
            if (!isPrepared) {
                if (currentSongIndex >= 0 && currentSongIndex < songs.size()) {
                    playSong(currentSongIndex);
                }
                return;
            }
            
            if (requestAudioFocus()) {
                mediaSession.setActive(true);
                play();
            }
        }
        
        @Override
        public void onPause() {
            pause();
        }
        
        @Override
        public void onStop() {
            stop();
            mediaSession.setActive(false);
            stopSelf();
        }
        
        @Override
        public void onSkipToNext() {
            playNext();
        }
        
        @Override
        public void onSkipToPrevious() {
            playPrevious();
        }
        
        @Override
        public void onSeekTo(long pos) {
            seekTo((int) pos);
        }
    }
    
    private Notification createNotification() {
        if (mediaSession == null) return createBasicNotification();
        
        Song currentSong = getCurrentSong();
        if (currentSong == null) {
            return createBasicNotification();
        }
        
        // 获取专辑封面
        Bitmap albumArt = null;
        try {
            Uri albumArtUri = mediaScanner.getAlbumArtUri(currentSong.getAlbumId());
            albumArt = BitmapFactory.decodeStream(getContentResolver().openInputStream(albumArtUri));
        } catch (Exception e) {
            albumArt = BitmapFactory.decodeResource(getResources(), R.drawable.default_album_art);
        }
        
        // 创建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_music_note)
                .setLargeIcon(albumArt)
                .setContentTitle(currentSong.getTitle())
                .setContentText(currentSong.getArtist())
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .setOnlyAlertOnce(true)
                .setShowWhen(false);
        
        // 设置通知样式
        androidx.media.app.NotificationCompat.MediaStyle style = 
                new androidx.media.app.NotificationCompat.MediaStyle()
                        .setMediaSession(mediaSession.getSessionToken())
                        .setShowActionsInCompactView(0, 1, 2);
        
        builder.setStyle(style);
        
        // 创建Intent和PendingIntent
        Intent prevIntent = new Intent(this, MusicPlayerService.class).setAction("PREV");
        PendingIntent prevPendingIntent = PendingIntent.getService(this, 0, prevIntent, 
                PendingIntent.FLAG_IMMUTABLE);
                
        Intent playPauseIntent = new Intent(this, MusicPlayerService.class)
                .setAction(isPlaying() ? "PAUSE" : "PLAY");
        PendingIntent playPausePendingIntent = PendingIntent.getService(this, 1, playPauseIntent, 
                PendingIntent.FLAG_IMMUTABLE);
                
        Intent nextIntent = new Intent(this, MusicPlayerService.class).setAction("NEXT");
        PendingIntent nextPendingIntent = PendingIntent.getService(this, 2, nextIntent, 
                PendingIntent.FLAG_IMMUTABLE);
        
        // 添加媒体控制按钮
        builder.addAction(new NotificationCompat.Action(
                R.drawable.ic_skip_previous,
                "Previous",
                prevPendingIntent));
                
        builder.addAction(new NotificationCompat.Action(
                isPlaying() ? R.drawable.ic_pause : R.drawable.ic_play,
                isPlaying() ? "Pause" : "Play",
                playPausePendingIntent));
                                
        builder.addAction(new NotificationCompat.Action(
                R.drawable.ic_skip_next,
                "Next",
                nextPendingIntent));
        
        return builder.build();
    }
    
    private Notification createBasicNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_music_note)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(getString(R.string.no_songs_found))
                .setPriority(NotificationCompat.PRIORITY_LOW);
        
        return builder.build();
    }
    
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "VibePlayer Music Channel",
                    NotificationManager.IMPORTANCE_LOW);
            
            channel.setDescription("VibePlayer音乐播放通知");
            channel.enableLights(false);
            channel.enableVibration(false);
            channel.setShowBadge(false);
            
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }
    
    private void updatePlaybackState(int state) {
        if (mediaSession == null || stateBuilder == null) return;
        
        stateBuilder.setState(state, getCurrentPosition(), 1.0f);
        mediaSession.setPlaybackState(stateBuilder.build());
        
        // 更新通知
        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, createNotification());
    }
    
    /**
     * 设置播放列表
     * @param songs 歌曲列表
     */
    public void setSongs(List<Song> songs) {
        this.songs = songs;
    }
    
    /**
     * 设置当前播放歌曲索引并开始播放
     * @param songIndex 歌曲索引
     */
    public void playSong(int songIndex) {
        if (songIndex < 0 || songIndex >= songs.size()) {
            return;
        }
        
        currentSongIndex = songIndex;
        playSong(songs.get(currentSongIndex));
    }
    
    /**
     * 播放指定歌曲
     * @param song 要播放的歌曲
     */
    public void playSong(Song song) {
        if (song == null) {
            return;
        }
        
        // 请求音频焦点
        if (!requestAudioFocus()) {
            Toast.makeText(this, "无法获取音频焦点", Toast.LENGTH_SHORT).show();
            return;
        }
        
        try {
            mediaPlayer.reset();
            isPrepared = false;
            
            // 设置数据源
            mediaPlayer.setDataSource(song.getPath());
            
            // 异步准备
            mediaPlayer.prepareAsync();
            
            // 添加到最近播放
            databaseHelper.addToRecentlyPlayed(song.getId());
            
            // 更新通知
            updateNotification();
            
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "播放错误: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 播放或暂停
     */
    public void playPause() {
        if (mediaPlayer.isPlaying()) {
            pause();
        } else {
            play();
        }
    }
    
    /**
     * 播放
     */
    public void play() {
        if (!isPrepared) {
            return;
        }
        
        if (!requestAudioFocus()) {
            return;
        }
        
        mediaPlayer.start();
        updatePlaybackState(PlaybackStateCompat.STATE_PLAYING);
        updateNotification();
    }
    
    /**
     * 暂停
     */
    public void pause() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            updatePlaybackState(PlaybackStateCompat.STATE_PAUSED);
            updateNotification();
        }
    }
    
    /**
     * 停止
     */
    public void stop() {
        mediaPlayer.stop();
        isPrepared = false;
        updatePlaybackState(PlaybackStateCompat.STATE_STOPPED);
        abandonAudioFocus();
    }
    
    /**
     * 播放下一首歌曲
     */
    public void playNext() {
        if (songs.isEmpty()) {
            return;
        }
        
        int nextIndex = -1;
        
        switch (playMode) {
            case PLAY_MODE_NORMAL:
            case PLAY_MODE_REPEAT_ALL:
                nextIndex = (currentSongIndex + 1) % songs.size();
                break;
            case PLAY_MODE_REPEAT_ONE:
                nextIndex = currentSongIndex;
                break;
            case PLAY_MODE_SHUFFLE:
                nextIndex = random.nextInt(songs.size());
                break;
        }
        
        if (nextIndex >= 0) {
            playSong(nextIndex);
        }
    }
    
    /**
     * 播放上一首歌曲
     */
    public void playPrevious() {
        if (songs.isEmpty()) {
            return;
        }
        
        int prevIndex = -1;
        
        switch (playMode) {
            case PLAY_MODE_NORMAL:
            case PLAY_MODE_REPEAT_ALL:
                prevIndex = (currentSongIndex - 1 + songs.size()) % songs.size();
                break;
            case PLAY_MODE_REPEAT_ONE:
                prevIndex = currentSongIndex;
                break;
            case PLAY_MODE_SHUFFLE:
                prevIndex = random.nextInt(songs.size());
                break;
        }
        
        if (prevIndex >= 0) {
            playSong(prevIndex);
        }
    }
    
    /**
     * 设置播放模式
     * @param mode 播放模式
     */
    public void setPlayMode(int mode) {
        if (mode >= PLAY_MODE_NORMAL && mode <= PLAY_MODE_SHUFFLE) {
            this.playMode = mode;
            
            // 如果是随机播放模式，打乱播放列表
            if (mode == PLAY_MODE_SHUFFLE) {
                shufflePlaylist();
            }
        }
    }
    
    /**
     * 获取当前播放模式
     * @return 播放模式
     */
    public int getPlayMode() {
        return playMode;
    }
    
    /**
     * 获取当前播放歌曲
     * @return 当前歌曲，如果没有则返回null
     */
    public Song getCurrentSong() {
        if (currentSongIndex >= 0 && currentSongIndex < songs.size()) {
            return songs.get(currentSongIndex);
        }
        return null;
    }
    
    /**
     * 获取当前播放位置
     * @return 当前播放位置（毫秒）
     */
    public int getCurrentPosition() {
        if (isPrepared) {
            return mediaPlayer.getCurrentPosition();
        }
        return 0;
    }
    
    /**
     * 获取歌曲总时长
     * @return 歌曲总时长（毫秒）
     */
    public int getDuration() {
        if (isPrepared) {
            return mediaPlayer.getDuration();
        }
        return 0;
    }
    
    /**
     * 跳转到指定位置
     * @param position 目标位置（毫秒）
     */
    public void seekTo(int position) {
        if (isPrepared) {
            mediaPlayer.seekTo(position);
        }
    }
    
    /**
     * 是否正在播放
     * @return 是否正在播放
     */
    public boolean isPlaying() {
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }
    
    /**
     * 是否已准备好
     * @return 是否已准备好
     */
    public boolean isPrepared() {
        return isPrepared;
    }
    
    /**
     * 获取当前播放索引
     * @return 当前播放索引
     */
    public int getCurrentSongIndex() {
        return currentSongIndex;
    }
    
    /**
     * 打乱播放列表
     */
    public void shufflePlaylist() {
        if (songs.isEmpty()) {
            return;
        }
        
        Song currentSong = null;
        if (currentSongIndex >= 0 && currentSongIndex < songs.size()) {
            currentSong = songs.get(currentSongIndex);
        }
        
        Collections.shuffle(songs);
        
        if (currentSong != null) {
            currentSongIndex = songs.indexOf(currentSong);
        }
    }
    
    /**
     * 获取MediaPlayer对象
     * @return MediaPlayer对象
     */
    public MediaPlayer getMediaPlayer() {
        return mediaPlayer;
    }
    
    /**
     * 更新通知
     */
    private void updateNotification() {
        NotificationManager notificationManager = 
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, createNotification());
    }
    
    /**
     * 请求音频焦点
     * @return 是否获取到音频焦点
     */
    private boolean requestAudioFocus() {
        int result;
        
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            audioFocusRequest = new AudioFocusRequest.Builder(AudioManager.AUDIOFOCUS_GAIN)
                    .setOnAudioFocusChangeListener(this)
                    .setAudioAttributes(new AudioAttributes.Builder()
                            .setUsage(AudioAttributes.USAGE_MEDIA)
                            .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
                            .build())
                    .build();
            
            result = audioManager.requestAudioFocus(audioFocusRequest);
        } else {
            result = audioManager.requestAudioFocus(this, AudioManager.STREAM_MUSIC, 
                    AudioManager.AUDIOFOCUS_GAIN);
        }
        
        return result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED;
    }
    
    /**
     * 放弃音频焦点
     */
    private void abandonAudioFocus() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            if (audioFocusRequest != null) {
                audioManager.abandonAudioFocusRequest(audioFocusRequest);
            }
        } else {
            audioManager.abandonAudioFocus(this);
        }
    }
    
    @Override
    public void onPrepared(MediaPlayer mp) {
        isPrepared = true;
        play();
    }
    
    @Override
    public void onCompletion(MediaPlayer mp) {
        // 根据播放模式决定下一步操作
        switch (playMode) {
            case PLAY_MODE_NORMAL:
                // 顺序播放模式，播放下一首，如果是最后一首则停止
                if (currentSongIndex < songs.size() - 1) {
                    playNext();
                } else {
                    stop();
                }
                break;
            case PLAY_MODE_REPEAT_ONE:
                // 单曲循环模式，重新播放当前歌曲
                playSong(currentSongIndex);
                break;
            case PLAY_MODE_REPEAT_ALL:
                // 列表循环模式，播放下一首
                playNext();
                break;
            case PLAY_MODE_SHUFFLE:
                // 随机播放模式，随机播放一首
                int nextIndex = random.nextInt(songs.size());
                playSong(nextIndex);
                break;
        }
    }
    
    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        // 发生错误时重置MediaPlayer
        isPrepared = false;
        mediaPlayer.reset();
        
        // 尝试播放下一首
        if (!songs.isEmpty()) {
            playNext();
        }
        
        return true;
    }
    
    @Override
    public void onAudioFocusChange(int focusChange) {
        switch (focusChange) {
            case AudioManager.AUDIOFOCUS_GAIN:
                // 获得音频焦点
                if (mediaPlayer == null) {
                    initMediaPlayer();
                } else if (!mediaPlayer.isPlaying() && wasPlaying) {
                    play();
                }
                mediaPlayer.setVolume(1.0f, 1.0f);
                wasPlaying = false;
                break;
            case AudioManager.AUDIOFOCUS_LOSS:
                // 永久失去音频焦点
                wasPlaying = isPlaying();
                if (isPlaying()) {
                    pause();
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
                // 暂时失去音频焦点
                wasPlaying = isPlaying();
                if (isPlaying()) {
                    pause();
                }
                break;
            case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
                // 暂时失去音频焦点，但可以继续播放（音量降低）
                if (isPlaying()) {
                    mediaPlayer.setVolume(0.2f, 0.2f);
                }
                break;
        }
    }
    
    /**
     * 处理Service的启动命令
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String action = intent != null ? intent.getAction() : null;
        if (action != null) {
            switch (action) {
                case "PLAY":
                    play();
                    break;
                case "PAUSE":
                    pause();
                    break;
                case "PREV":
                    playPrevious();
                    break;
                case "NEXT":
                    playNext();
                    break;
            }
        }
        return START_NOT_STICKY;
    }
    
    public class MusicBinder extends Binder {
        public MusicPlayerService getService() {
            return MusicPlayerService.this;
        }
    }
} 